import React, { useState, useEffect } from 'react'
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { restrictToVerticalAxis } from '@dnd-kit/modifiers'
import {
  arrayMove,
  SortableContext,
  useSortable,
  verticalListSortingStrategy
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import './index.modules.scss'
import { baseURL } from '@/http/request'
import {
  PlusOutlined,
  LeftOutlined,
  FolderOpenOutlined
} from '@ant-design/icons'
import uuid from '@/components/js/uuid'
import {
  Space,
  Table,
  Button,
  Image,
  Modal,
  Card,
  message,
  Form,
  Upload,
  Input,
  Popconfirm,
  Pagination,
  Select
} from 'antd'
import { productAdd, productChange } from '@/http/api/resource'
let pageData = {
  page: 1,
  size: 10,
  total: 0
}
let pageData2 = {
  page: 1,
  size: 10,
  total: 0
}

const Row = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key']
  })
  const style = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging
      ? {
          position: 'relative',
          zIndex: 9999
        }
      : {})
  }
  return (
    <tr
      {...props}
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
    />
  )
}
const Row2 = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key']
  })
  const style = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging
      ? {
          position: 'relative',
          zIndex: 9999
        }
      : {})
  }
  return (
    <tr
      {...props}
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
    />
  )
}
const App = ({ isShowAddFn, myData, type }) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
    console.log(myData)
  }, [])
  const [dataSource, setDataSource] = useState([])
  const [dataSource2, setDataSource2] = useState([])
  const [isShowAdd, serIsShowAdd] = useState(false)
  const [isShowAdd2, serIsShowAdd2] = useState(false)
  const [form] = Form.useForm()
  const [form2] = Form.useForm()
  const [headerData] = Form.useForm()
  const { TextArea } = Input
  const columns = [
    {
      title: '图片',
      dataIndex: 'image',
      align: 'center',
      render: (image) => {
        return (
          <Image
            width={60}
            height={60}
            src={image}
            fallback=""
          />
        )
      }
    },
    {
      title: '内容名称',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          {type != 0 ? (
            <Button
              type="primary"
              onClick={() => {
                showModalAdd(data)
              }}
            >
              编辑
            </Button>
          ) : (
            <></>
          )}
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              setDataSource(
                dataSource.filter((item) => {
                  if (item.key != data.key) {
                    return {
                      ...item
                    }
                  }
                })
              )

              // DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            {type != 0 ? (
              <Button type="primary" danger>
                删除
              </Button>
            ) : (
              <></>
            )}
          </Popconfirm>
        </Space>
      )
    }
  ]
  const columns2 = [
    {
      title: '图片',
      dataIndex: 'image',
      align: 'center',
      render: (image) => {
        return (
          <Image
            width={60}
            height={60}
            src={image}
            fallback=""
          />
        )
      }
    },
    {
      title: '内容文本',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          {type != 0 ? (
            <Button
              type="primary"
              onClick={() => {
                showModalAdd2(data)
              }}
            >
              编辑
            </Button>
          ) : (
            <></>
          )}

          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              setDataSource2(
                dataSource2.filter((item) => {
                  if (item.key != data.key) {
                    return {
                      ...item
                    }
                  }
                })
              )
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            {type != 0 ? (
              <Button type="primary" danger>
                删除
              </Button>
            ) : (
              <></>
            )}
          </Popconfirm>
        </Space>
      )
    }
  ]
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1
      }
    })
  )
  const sensors2 = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1
      }
    })
  )
  // 获取列表
  const getList = async () => {
    if (myData._id) {
      let listData = JSON.parse(myData?.swiper)
      let listData2 = JSON.parse(myData?.images)
      setDataSource(listData)
      setDataSource2(listData2)
      headerData.setFieldsValue(myData)
    }
  }
  const onDragEnd = ({ active, over }) => {
    if (active.id !== over?.id) {
      setDataSource((prev) => {
        const activeIndex = prev.findIndex((i) => i.key === active.id)
        const overIndex = prev.findIndex((i) => i.key === over?.id)
        return arrayMove(prev, activeIndex, overIndex)
      })
    }
  }
  const onDragEnd2 = ({ active, over }) => {
    if (active.id !== over?.id) {
      setDataSource2((prev) => {
        const activeIndex = prev.findIndex((i) => i.key === active.id)
        const overIndex = prev.findIndex((i) => i.key === over?.id)
        return arrayMove(prev, activeIndex, overIndex)
      })
    }
  }
  const showModalAdd = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      form.setFieldsValue(data)
    }
    serIsShowAdd(true)
  }
  const showModalAdd2 = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      form2.setFieldsValue(data)
    }
    serIsShowAdd2(true)
  }
  // 添加轮播图
  const onFinish = async (data) => {
    data.image = data.imageurl.fileList[0].response.image_url
    delete data.imageurl
    data.key = uuid()
    setDataSource([...dataSource, data])
    serIsShowAdd(false)
    form.resetFields()
  }
  const onFinishFailed = (data, a, b) => {
    console.log(data, a, b)
  }
  // 添加介绍图
  const onFinish2 = async (data) => {
    data.image = data.imageurl.fileList[0].response.image_url
    delete data.imageurl
    data.key = uuid()
    setDataSource2([...dataSource2, data])
    serIsShowAdd2(false)
    form2.resetFields()
  }
  const onFinishFailed2 = (data, a, b) => {
    console.log(data, a, b)
  }
  // 分页
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
  }
  const pageChangeFn2 = (page, pageSize) => {
    pageData2.page = page
    pageData2.size = pageSize
  }

  // 添加
  const headerAddFn = async (data) => {
    try {
      if (myData._id) {
        if (data.coverImg.fileList) {
          data.coverImg = data.coverImg.fileList[0].response.image_url
        }
        data.swiper = dataSource
        data.images = dataSource2
        data._id = myData._id
        await productChange(data)
        messageApi.success('修改成功')
      } else {
        data.coverImg = data.coverImg.fileList[0].response.image_url
        data.appid = localStorage.getItem('appid')
        if (dataSource.length == 0 || dataSource2.length == 0) {
          throw new Error('请添加轮播图或商品图')
        }
        data.swiper = dataSource
        data.images = dataSource2
        await productAdd(data)
        messageApi.success('添加成功')
      }
      setTimeout(() => {
        isShowAddFn()
      }, 500)
    } catch (err) {
      messageApi.error('失败请重试')
    }
  }
  return (
    <div>
      <Card>
        <div className="HederBox alignCenter">
          <LeftOutlined
            style={{ fontSize: '50px' }}
            onClick={() => {
              isShowAddFn()
              setDataSource([])
              setDataSource2([])
              form.resetFields()
              form2.resetFields()
            }}
          />
          <Form
            onFinish={headerAddFn}
            labelCol={{
              span: 8
            }}
            wrapperCol={{
              span: 14
            }}
            layout="inline"
            form={headerData}
            style={{
              maxWidth: 'none'
            }}
          >
            <Form.Item label="选择图片" name="coverImg">
              <Upload
                accept=".jpg,.png"
                maxCount={1}
                action={baseURL + 'api/uploadAvatar'}
              >
                <Input
                  disabled={type == 0 ? true : false}
                  placeholder="请选择图片"
                  suffix={<FolderOpenOutlined />}
                />
              </Upload>
            </Form.Item>
            <Form.Item label="产品名称" name="name">
              <Input
                disabled={type == 0 ? true : false}
                placeholder="请输入产品名称"
              />
            </Form.Item>
            <Form.Item label="产品标题" name="title">
              <Input
                disabled={type == 0 ? true : false}
                placeholder="请输入产品标题"
              />
            </Form.Item>
            <Form.Item label="产品介绍" name="introduce">
              <TextArea
                autoSize={{ minRows: 1, maxRows: 6 }}
                disabled={type == 0 ? true : false}
              />
            </Form.Item>
            <Form.Item label="产品类型" name="type">
              <Select
                style={{ width: '120px' }}
                options={[
                  { value: '漆面膜', label: '漆面膜' },
                  { value: '改色膜', label: '改色膜' },
                  { value: '车顶膜', label: '车顶膜' },
                  { value: '太阳膜', label: '太阳膜' }
                ]}
              />
            </Form.Item>
            {type == 1 ? (
              <Form.Item>
                <Button htmlType="submit" type="primary">
                  修改
                </Button>
              </Form.Item>
            ) : type == 3 ? (
              <Form.Item>
                <Button htmlType="submit" type="primary">
                  添加
                </Button>
              </Form.Item>
            ) : (
              <></>
            )}
          </Form>
        </div>
        <div className="headerButton">
          <div className="title">轮播图</div>
          {type != 0 ? (
            <Button
              type="primary"
              onClick={() => {
                serIsShowAdd(true)
              }}
            >
              添加轮播图
            </Button>
          ) : (
            <></>
          )}
        </div>
        <DndContext
          sensors={sensors}
          modifiers={[restrictToVerticalAxis]}
          onDragEnd={onDragEnd}
        >
          <SortableContext
            items={dataSource.map((i) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              pagination={false}
              bordered
              components={{
                body: {
                  row: Row
                }
              }}
              rowKey="key"
              columns={columns}
              dataSource={dataSource}
            />
          </SortableContext>
        </DndContext>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
        <div>
          <Modal
            title="添加"
            footer={[]}
            onCancel={() => {
              serIsShowAdd(false)
              form.resetFields()
            }}
            open={isShowAdd}
          >
            <Form
              labelCol={{
                span: 5
              }}
              wrapperCol={{
                span: 14
              }}
              layout="horizontal"
              style={{
                maxWidth: 800
              }}
              form={form}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                label="图片名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入名称'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="图片"
                name="imageurl"
                rules={[
                  {
                    required: true,
                    message: '请选择图片'
                  }
                ]}
              >
                <Upload
                  accept=".jpg,.png"
                  maxCount={1}
                  action={baseURL + 'api/uploadAvatar'}
                  listType="picture-card"
                >
                  <button
                    style={{
                      border: 0,
                      background: 'none'
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                    <div
                      style={{
                        marginTop: 8
                      }}
                    ></div>
                  </button>
                </Upload>
              </Form.Item>
              <Form.Item
                label="图片备注"
                name="remark"
                rules={[
                  {
                    required: true,
                    message: '请输入备注'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                wrapperCol={{
                  offset: 6,
                  span: 16
                }}
              >
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button
                  style={{ marginLeft: '10px' }}
                  type="primary"
                  onClick={() => {
                    form.resetFields()
                    serIsShowAdd(false)
                  }}
                >
                  取消
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </Card>
      {/* 图片 */}
      <Card>
        <div className="headerButton">
          <div className="title">图片</div>
          {type != 0 ? (
            <Button
              type="primary"
              onClick={() => {
                serIsShowAdd2(true)
              }}
            >
              添加内容
            </Button>
          ) : (
            <></>
          )}
        </div>
        <DndContext
          sensors={sensors2}
          modifiers={[restrictToVerticalAxis]}
          onDragEnd={onDragEnd2}
        >
          <SortableContext
            items={dataSource2.map((i) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              pagination={false}
              bordered
              components={{
                body: {
                  row: Row2
                }
              }}
              rowKey="key"
              columns={columns2}
              dataSource={dataSource2}
            />
          </SortableContext>
        </DndContext>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn2}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
        <div>
          <Modal
            title="添加"
            footer={[]}
            onCancel={() => {
              serIsShowAdd2(false)
              form2.resetFields()
            }}
            open={isShowAdd2}
          >
            <Form
              labelCol={{
                span: 5
              }}
              wrapperCol={{
                span: 14
              }}
              layout="horizontal"
              style={{
                maxWidth: 800
              }}
              form={form2}
              onFinish={onFinish2}
              onFinishFailed={onFinishFailed2}
            >
              <Form.Item
                label="图片名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入名称'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="图片"
                name="imageurl"
                rules={[
                  {
                    required: true,
                    message: '请选择图片'
                  }
                ]}
              >
                <Upload
                  accept=".jpg,.png"
                  maxCount={1}
                  action={baseURL + 'api/uploadAvatar'}
                  listType="picture-card"
                >
                  <button
                    style={{
                      border: 0,
                      background: 'none'
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                    <div
                      style={{
                        marginTop: 8
                      }}
                    ></div>
                  </button>
                </Upload>
              </Form.Item>
              <Form.Item
                label="图片备注"
                name="remark"
                rules={[
                  {
                    required: true,
                    message: '请输入备注'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                wrapperCol={{
                  offset: 6,
                  span: 16
                }}
              >
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button
                  style={{ marginLeft: '10px' }}
                  type="primary"
                  onClick={() => {
                    form2.resetFields()
                    serIsShowAdd2(false)
                  }}
                >
                  取消
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </Card>
      {contextHolder}
    </div>
  )
}
export default App
